/**
 *	单位管理主页
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-29
 */

package com.framework.Controller.api;


import com.framerock.db.DB;
import com.framerock.server.Response;
import com.framerock.baselib.CDate;
import com.framerock.baselib.Json;
import com.framerock.baselib.Patter;
import com.framerock.baselib.Rock;
import com.framework.Chajian.ChajianReim;
import com.framework.Chajian.Chajianrockfile;
import com.framework.Flow.Flow;
import com.framework.ACore.Model;
import com.framework.Model.ModelCompany;
import com.framework.Model.ModelDept;
import com.framework.Model.ModelFlowunit;
import com.framework.Model.ModelMode;
import com.framework.Model.ModelOption;
import com.framework.Model.ModelReim;

import java.util.ArrayList;
import java.util.Map;

public class ControllerCompany extends ControllerApiCompany {



    protected String runAction(String action)
    {
        if(action.equals("userdata"))return userdata();
        if(action.equals("savelogo"))return savefields("logo");
        if(action.equals("savename"))return savefields("name");
        if(action.equals("savehmode"))return savefields("hmode");
        if(action.equals("savenameshort"))return savefields("nameshort");
        if(action.equals("flowmode"))return flowmode();
        if(action.equals("flowmodesave"))return flowmodesave();
        if(action.equals("exit"))return exit();
        if(action.equals("homeme"))return homeme();
        if(action.equals("deptuser"))return deptuser();
        return super.runAction(action);
    }

    public String index()
    {
        Model obj = Model.get(this.nDb, "usera");
        Json json = new Json();
        json.putVal("info", mRequest.getCompanyinfo());
        json.putInt("usershu", obj.getCount("`cid`="+mRequest.COMPANYID+""));
        json.putInt("usershuwjh", obj.getCount("`cid`="+mRequest.COMPANYID+" and `state`=0"));
        return Response.returnSuccess(json.getJson());
    }

    //选中用户
    public String userdata()
    {
        Json json = new Json();
        String changetype = mRequest.get("changetype");

        String deptarr = Json.getListString(Model.get(this.nDb,"dept").getAll("`cid`="+mRequest.COMPANYID+"", "id,name,pid", "`sort`"));
        json.putVal("deptarr", deptarr);

        String userarr = "[]",grouparr="[]";
        if(changetype.indexOf("user")>-1) {
            userarr  = Json.getListString(ModelCompany.get(this.nDb).companyUsera(mRequest.COMPANYID, ""));
        }

        json.putVal("userarr", userarr);
        json.putVal("grouparr", grouparr);

        return Response.returnSuccess(json.getJson());
    }

    //保存字段
    private String savefields(String fields){
        if(mRequest.USEATYPE==0)return Response.returnError("not auth");
        String value = mRequest.post("value");
        if(Rock.isEmpt(value))return Response.returnError("value is empty");
        ModelCompany.get(this.nDb).update("`"+fields+"`='"+value+"'", mRequest.COMPANYID);
        return Response.returnSuccess("ok");
    }


    //读取可选择的模块
    public String flowmode()
    {
        Json json = new Json();
        json.putVal("rows", Json.getListString(new ModelMode(this.nDb).getSelarr(mRequest.COMPANYID, "")));
        return Response.returnSuccess(json.getJson());
    }

    //保存选择的模块
    public String flowmodesave()
    {
        String sid = mRequest.post("sid");
        if(Rock.isEmpt(sid) && !Patter.isnumber(sid))return Response.returnError("params sid error");
        ArrayList<Map<String, String>> rows = new ModelMode(this.nDb).getSelarr(mRequest.COMPANYID, sid);
        Map<String, String> da,da1;
        if(rows != null)for(int i=0;i<rows.size();i++){
            da1= rows.get(i);
            da = Rock.getMap(new String[]{
                    "name",da1.get("name"),
                    "modeid",da1.get("id"),
                    "mknum",da1.get("num"),
                    "icons",da1.get("imgurl"),
                    "type",da1.get("type"),
                    "cid",mRequest.COMPANYID,
            });
            int mid = this.nDb.insert(DB.chuliPerfix("flowunit"), da);
            Flow flow   = Flow.get(this.nDb, da1.get("num"), mRequest);
            flow.initFunit(mid+"");
            flow.flowUnitadd();
        }
        return Response.returnSuccess("ok");
    }


    /**
     * 进入单位主页数据，读取菜单应用和回话信息
     * */
    public String data()
    {
        int hmode = Integer.parseInt(mRequest.get("hmode","0"));
        Json json = new Json();

        //读取菜单
        if(hmode==0) {
            String where = "";
            if (mRequest.USEATYPE == 0) {
                where = " and `ispir`=2";
            } else {
                where = " and `ispir` in(2,3)";
            }
            String rowsstr = Json.getListString(Model.get(this.nDb, "menu").getAll("`status`=1 " + where + "", "*", "`pid` asc, `sort` asc"));
            json.putVal("menuarr", rowsstr);
        }

        json.putVal("companyinfo", Rock.getMap(new String[]{
                "name", mRequest.getCompanyrs("name"),
                "logo", mRequest.getCompanyrs("logo"),
                "num", mRequest.getCompanyrs("num"),
                "nameshort", mRequest.getCompanyrs("nameshort"),
                "id", mRequest.getCompanyrs("id"),
        }));

        //IM形式
        if(hmode==1) {
            String deptarr = Json.getListString(Model.get(this.nDb, "dept").getAll("`cid`=" + mRequest.COMPANYID + "", "id,name,pid", "`sort`"));
            json.putVal("deptarr", deptarr);

            ModelReim obj = new ModelReim(this.nDb);
            obj.setRequest(mRequest);
            json.putVal("historyarr", obj.getHistory(""));
            json.putVal("grouparr", obj.getGroupArr(mRequest.USEAID, mRequest.USERID));
        }

        json.putVal("rockfile", new Chajianrockfile(this.nDb).getInfo());
        json.putVal("systemtitle", new ModelOption(this.nDb).getVal("systemtitle"));

        //读取平台个人信息
        json.putVal("userinfo", Rock.getMap(new String[]{
                "id",mRequest.getLoginrs("id"),
                "name",mRequest.getLoginrs("name"),
                "mobile",mRequest.getLoginrs("mobile"),
                "face",mRequest.getLoginrs("face"),
                "type",mRequest.getLoginrs("type"),
        }));

        //读取单位下个人信息
        json.putVal("useainfo", Rock.getMap(new String[]{
                "id",mRequest.getUserars("id"),
                "deptname",mRequest.getUserars("deptname"),
                "name",mRequest.getUserars("name"),
                "ranking",mRequest.getUserars("ranking"),
                "type",mRequest.getUserars("type"),
                "mobile",mRequest.getUserars("mobile"),
                "companyname",mRequest.getCompanyrs("name")
        }));

        //读取应用
        json.putVal("agentarr", ModelFlowunit.get(this.nDb).setRequests(mRequest).getAgent(mRequest.COMPANYID,mRequest.getUserainfo()));

        //读取模块类型对应图标mtypeicon
        json.putVal("mtypeicon", ModelOption.get(this.nDb).getData("mtypeicon","value"));

        //reim服务端
        json.putVal("reim", ChajianReim.obj(this.nDb).getInfo());

        json.putVal("nowdt", CDate.now());


        return Response.returnSuccess(json.getJson());
    }

    /**
     * 退出单位用户
     * */
    public String exit()
    {
        if(mRequest.USEATYPE==2)return Response.returnError("您是创建者无法退出，请先修改单位创建者");
        Model.get(this.nDb, "usera").update("`state`=2", mRequest.USEAID);
        return Response.returnSuccess();
    }

    /**
     * PC主页显示数据
     * */
    public String homeme()
    {
        String funids = mRequest.get("funids");
        if(Rock.isEmpt(funids) || !Patter.isnumber(funids))return Response.returnSuccess();

        Json json = new Json();
        ArrayList<Map<String, String>> kata = null,lrows;
        Flow flow;
        String cid = mRequest.COMPANYID,mknum,url,bstr;
        Map<String,String> rs,da;
        ModelFlowunit unitobj = ModelFlowunit.get(this.nDb);

        lrows = unitobj.getAll("`cid`="+cid+" AND `id` in("+funids+") AND `issx`=1", "*", "`sort` ASC");
        if(lrows != null)for(int i=0; i<lrows.size(); i++){
            rs      = lrows.get(i);
            mknum   = rs.get("mknum");
            url     = rs.get("url");
            if(!Rock.isEmpt(mknum)){
                flow = Flow.get(this.nDb,mknum, mRequest);
                flow.initFunit(rs.get("id"));
                bstr = flow.homeData(url);
                if(!Rock.isEmpt(bstr))json.putVal(mknum+url, bstr);
            }else{
                if(kata == null)kata = Rock.getMapList();
                da = Rock.getMap();
                da.put("id", rs.get("id"));
                da.put("name", rs.get("name"));
                da.put("icons", rs.get("icons"));
                da.put("url", url);
                kata.add(da);
            }
        }
        if(kata != null)json.putVal("kata", kata);

        return Response.returnSuccess(json.getJson());
    }

    /**
     * 读取部门下人员信息
     * */
    public String deptuser()
    {
        String id = mRequest.get("id");
        if(Rock.isEmpt(id) || !Patter.isnumber(id))return Response.returnSuccess();

        Json json = new Json();
        String deptidall = ModelDept.get(this.nDb).getDeptdown(id);
        ArrayList<Map<String, String>> userarr = ModelCompany.get(this.nDb).companyUsera(mRequest.COMPANYID, "a.`deptid` IN("+deptidall+")");
        json.putVal("userarr", userarr);

        return Response.returnSuccess(json.getJson());
    }
}
